package com.example.weight.householdWaste;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.weight.R;
import com.example.weight.config.Config;
import com.example.weight.util.Utility;
import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class ElectricRecordActivity extends AppCompatActivity {

    private String name, factory;

    private EditText powerAmmeter, illuminationAmmeter, comment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_electric_record);

        Intent previousIntent = getIntent();
        name = previousIntent.getStringExtra("name");
        factory = previousIntent.getStringExtra("factory");

        TitleBar titleBar = findViewById(R.id.electric_record_titleBar);
        titleBar.setOnTitleBarListener(new OnTitleBarListener() {
            @Override
            public void onLeftClick(View v) {
                finish();
            }

            @Override
            public void onTitleClick(View v) {}

            @Override
            public void onRightClick(View v) {}
        });

        powerAmmeter = findViewById(R.id.electric_record_power_ammeter);
        illuminationAmmeter = findViewById(R.id.electric_record_illumination_ammeter);
        comment = findViewById(R.id.electric_record_comment);

        RequestQueue queue = Volley.newRequestQueue(this);
        String url = Config.url + "/shlj/electricityMeter/getlast" + "?factory=" + factory;
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            if (!jsonObject.isNull("data")) {
                                JSONObject data = jsonObject.getJSONObject("data");
                                powerAmmeter.setText(data.getString("ePowerMeterReading"));
                                illuminationAmmeter.setText(data.getString("eLightingMeterReading"));
                                comment.setText(data.getString("remarks"));
                                Toast.makeText(ElectricRecordActivity.this,
                                        "今日已填写此表", Toast.LENGTH_SHORT).show();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(ElectricRecordActivity.this,
                        "获取信息失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        queue.add(stringRequest);
    }

    public void save(View view) {
        if (!Utility.isNumeric(illuminationAmmeter.getText().toString())) {
            Toast.makeText(this, "照明电表读数请填写数字", Toast.LENGTH_SHORT).show();
            return;
        }
        if (!Utility.isNumeric(powerAmmeter.getText().toString())) {
            Toast.makeText(this, "动力电表读数请填写数字", Toast.LENGTH_SHORT).show();
            return;
        }
        new AlertDialog.Builder(this)
            .setTitle("确定保存吗？")
            .setCancelable(false)
            .setNegativeButton("取消", ((dialog, which) ->
                    Toast.makeText(this, "取消保存", Toast.LENGTH_SHORT).show()))
            .setPositiveButton("确定", (dialog, which) ->{
                // 提交表单
                RequestQueue queue = Volley.newRequestQueue(this);
                String url = Config.url + "/shlj/electricityMeter/add";

                StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                        new Response.Listener<String>() {
                            @Override
                            public void onResponse(String response) {
                                Log.d("zys", response);
                                try {
                                    JSONObject jsonObject = new JSONObject(response);
                                    String code = jsonObject.getString("code");
//                                    powerAmmeter.setText("");
//                                    illuminationAmmeter.setText("");
//                                    comment.setText("");

                                    if (code.startsWith("2"))
                                        Toast.makeText(ElectricRecordActivity.this,
                                                "保存成功", Toast.LENGTH_SHORT).show();
                                    else
                                        Toast.makeText(ElectricRecordActivity.this,
                                                "保存失败", Toast.LENGTH_SHORT).show();
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(ElectricRecordActivity.this,
                                "保存失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                }) {
                    @Override
                    protected Map<String, String> getParams() {
                        Map<String, String> map=new HashMap<>();
                        map.put("ePowerMeterReadingstr", powerAmmeter.getText().toString());
                        map.put("eLightingMeterReadingstr", illuminationAmmeter.getText().toString());
                        map.put("readingPerson", name);
                        map.put("remarks", comment.getText().toString());
                        map.put("factory", factory);
                        return map;
                    }
                };
                stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                        DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                queue.add(stringRequest);
            })
            .show();
    }
}
